package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.config.RegexUtil;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.User;
import com.example.forum.services.IPictureService;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController //会返回数据,在body里面
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IPictureService pictureService;


    @ApiOperation("修改用户头像")
    @PostMapping("/uploadAvatar")
    public AppResult uploadPic(HttpServletRequest request,
            @ApiParam("头像文件") @RequestParam("avatar") MultipartFile file){
        //获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //判断文件是否为空
        if(null==file || file.isEmpty()){
            return AppResult.failed(ResultCode.UPDATE_AVATAR_IS_EMPTY);
        }

        //校验文件大小
        long maxFileSize = 2*1024*1024; // 2MB
        if(file.getSize()>maxFileSize){
            log.warn("文件大小超出了限制! {} bytes",file.getSize());
            return AppResult.failed(ResultCode.FAILED_UPDATE_AVATAR_oversize);
        }

        //调用
        String pic = pictureService.savePicture(file);
        if(StringUtil.isEmpty(pic)){
            log.warn("图片转换类型失败!");
            return AppResult.failed(ResultCode.FAILED_UPDATE_AVATAR);
        }
        userService.modifyAvatarUrl(user.getId(), pic);
        //查询最新的信息
        user = userService.selectById(user.getId());
        //更新session
        session.setAttribute(AppConfig.USER_SESSION,user);
        log.info("更新头像成功!");
        return AppResult.success(user);
    }

    /**
     * 创建新用户
     * @param username 用户名
     * @param nickname 用户昵称
     * @param password 密码
     * @param passwordRepeat 再次输入密码(确认密码)
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username, //@RequestParam 用来规定 url 中的参数是什么
                              @ApiParam("用户昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)
        || StringUtil.isEmpty(nickname) || StringUtil.isEmpty(passwordRepeat)){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            //controller层一般不会抛出异常,一般是由service层来抛出
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //校验密码是否与确认密码相同
        if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.getMessage());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        //校验密码是否至少有6位
        if(!RegexUtil.checkPassword(password)){
            log.warn("密码没有六位数!");
            return AppResult.failed(ResultCode.PASSWORD_NOT_SAFE);
        }

        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //生成盐
        String salt = UUIDUtil.UUID_32();
        String ciphertext = MD5Util.md5Salt(password,salt);
        user.setPassword(ciphertext);
        user.setSalt(salt);
        userService.createNormalUser(user);
        //返回 成功
        log.info("用户注册成功!");
        return AppResult.success();
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password){
        User user = userService.login(username,password);
        if(user==null){
            log.warn("用户登录失败,找不到该用户");
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //获取session
        HttpSession session = request.getSession(true); //没有session对象时要创建一个新的
        //将User设置到Session中
        session.setAttribute(AppConfig.USER_SESSION,user);
        //登录成功
        log.info("用户登录成功!");
        return AppResult.success();
    }

    /**
     * 获取用户信息
     * @param id
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户id")
                                       @RequestParam(value = "id",required = false) Long id){//说明 id 是一个非必传项
        User user = null;
        if(null==id){
            log.info("没有传入用户id,将从session中获取");
            HttpSession session = request.getSession(false);
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else{
            user = userService.selectById(id);
        }
        if(user==null){
            log.warn("没有找到目标用户!");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        log.info("获取当前用户信息成功!");
        return AppResult.success(user);
    }

    /**
     * 用户登出
     */
    @ApiOperation("用户退出登录")
    @GetMapping("logout")
    public AppResult logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if(session!=null){
            session.invalidate();//注销
        }
        //退出成功
        log.info("退出当前账号成功!");
        return AppResult.success();
    }

    /**
     * 修改用户个人信息
     */
    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult<User> modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                @ApiParam("电话号码") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark){
        if(StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && gender == null && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(phoneNum) && StringUtil.isEmpty(remark)){
            log.error("所有参数均为空!");
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        userService.modifyInfo(updateUser);
        //查询最新的信息
        user = userService.selectById(user.getId());
        //更新session
        session.setAttribute(AppConfig.USER_SESSION,user);
        log.info("修改个人信息成功!");
        return AppResult.success(user);
    }


    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //校验
        if(!newPassword.equals(passwordRepeat)){
            log.warn("两次输入的密码不相同!");
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        userService.modifyPassword(user.getId(),newPassword,oldPassword);

        //销毁session
        if(null != session){
            session.invalidate();        }

        log.info("修改密码成功!");
        return AppResult.success();
    }
}
